package glub.hlzds.mijia;


import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import com.alibaba.fastjson.JSONObject;


public class XiaoMi {
    private static String deviceId = "79QamcVRJwd7-sks";
    private static String sdkVersion = "accountsdk-18.11.26";
    private static String Cookie = "deviceId="+deviceId+"; sdkVersion="+sdkVersion+";";
    private static String username = "142381045"; //142381045
    private static String password = "a0123123";  //a0123123
    private static String ssecurity = "";

    public static void test() {
        https://account.xiaomi.com/pass/serviceLogin?_json=true&sid=xiaomiio


        Utils.logInfo = false;
        String url = "https://account.xiaomi.com/pass/serviceLogin?_json=true&sid=xiaomiio";

        HashMap<String, String> heads = new HashMap<String,String>();
        heads.put("Content-Type", "application/x-www-form-urlencoded");
        heads.put("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 8.1.0; ONEPLUS A5000 Build/OPM1.171019.011) MIOTWeex/2.0.2 (SmartHome;5.5.43;35D098176DB8665B0A7C711686A9539E;0.20.1;A;A7EDE321F22A8AC544FDAFAD13FC5DD8B6A53158;MI_APP_STORE;79QamcVRJwd7-sks) MIOTStore/20180406 (SmartHome;5.5.43;35D098176DB8665B0A7C711686A9539E;;A;A7EDE321F22A8AC544FDAFAD13FC5DD8B6A53158;MI_APP_STORE;79QamcVRJwd7-sks) APP/xiaomi.smarthome APPV/62916");
        heads.put("Cookie", Cookie);
        heads.put("Host", "account.xiaomi.com");
        heads.put("Connection", "Keep-Alive");
        heads.put("Accept-Encoding", "gzip");

        String ret = Utils.get(url,heads);
        ret = ret.replaceAll("&&&START&&&", "");
        JSONObject retJson = JSONObject.parseObject(ret);

        System.out.println(retJson.get("_sign"));
    }

    public static void login() throws Exception {
        String d = "h8V2e6:0bqc51:avtloQ#h8V2e6#W0FxJf#0Z75x4#yNx+NI:MQ==:T05FUExVUyBBNTAwMA==:MTU4NGJiYjM=:zwTOOJ:79Qamc:tlifxq:CzeZmH:NDYwMDExODUyMTA5NjA2:ODk4NjAxMTc4MzEwMTIwMTk1NDI=::NDYwMDE=::T25lUGx1cyA1";

        byte[] keyy = RSACoder.generateSymmetricKey().getEncoded();
        byte[] r = RSACoder.encrypt(d.getBytes(),keyy);
        String env = new String(Base64.encodeBase64(r));
        env = env.replaceAll("\\+", "\\-");


        byte[] aa = RSACoder.cipher(keyy,RSACoder.getCertificatePublicKey(RSACoder.x509Key),1);
        String envkey = new String(Base64.encodeBase64(aa));
        String url = "https://account.xiaomi.com/pass/serviceLoginAuth2";

        HashMap<String, String> data = new HashMap<String,String>();
        data.put("qs", "%3F_json%3Dtrue%26sid%3Dxiaomiio");
        data.put("env", "123123"); //可以随便传
        data.put("user", username);
        data.put("_sign", "7RoEnWWgpjzsTGA0t/VgVXgydtc=");
        System.out.println(Encript.stringMD5(password) );
        data.put("hash", Encript.stringMD5(password));
        data.put("envKey", "123123"); //可以随便传
        data.put("callback", "https://sts.api.io.mi.com/sts");
        data.put("_json", "true");
        data.put("sid", "xiaomiio");

        HashMap<String, String> heads = new HashMap<String,String>();
        heads.put("Content-Type", "application/x-www-form-urlencoded");
        heads.put("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 8.1.0; ONEPLUS A5000 Build/OPM1.171019.011) MIOTWeex/2.0.2 (SmartHome;5.5.43;35D098176DB8665B0A7C711686A9539E;0.20.1;A;A7EDE321F22A8AC544FDAFAD13FC5DD8B6A53158;MI_APP_STORE;79QamcVRJwd7-sks) MIOTStore/20180406 (SmartHome;5.5.43;35D098176DB8665B0A7C711686A9539E;;A;A7EDE321F22A8AC544FDAFAD13FC5DD8B6A53158;MI_APP_STORE;79QamcVRJwd7-sks) APP/xiaomi.smarthome APPV/62916");
        heads.put("Cookie", Cookie);
        heads.put("Host", "account.xiaomi.com");
        heads.put("Connection", "Keep-Alive");
        heads.put("Accept-Encoding", "gzip");
        heads.put("Content-Length", data.toString().length()-2+"");

        Map<String,String> responseMap = Utils.postXiomi(url,heads,data);
        Utils.retDatas.put("login", responseMap.get("body"));
        Utils.retDatas.put("extension-pragma", responseMap.get("extension-pragma"));
    }


    public static byte[] d(byte[] arg1) throws Exception{
        MessageDigest v0 = MessageDigest.getInstance("SHA-256");
        v0.update(arg1);
        return v0.digest();
    }

    public static byte[] a(byte[] arg4, byte[] arg5) {
        byte[] v0 = new byte[arg4.length + arg5.length];
        System.arraycopy(arg4, 0, v0, 0, arg4.length);
        System.arraycopy(arg5, 0, v0, arg4.length, arg5.length);
        return v0;
    }

    public static String b(long arg4) throws Exception {
        ByteArrayOutputStream v0 = new ByteArrayOutputStream();
        DataOutputStream v1 = new DataOutputStream(((OutputStream)v0));

        Random b = new SecureRandom();
        v1.writeLong(b.nextLong());
//      v1.writeLong(Long.parseLong("474899402"));
        v1.writeInt(((int)(arg4 / 60000)));
        v1.flush();

        return new String(Base64.encodeBase64(v0.toByteArray()));
    }
    public static byte[] encodeSHA1(byte[] data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        return md.digest(data);
    }


    public static void loginServer(String url,String host) throws Exception {
        Map<String,String> heads = new HashMap<String,String>();
        heads.put("Content-Type", "application/x-www-form-urlencoded");
        heads.put("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 8.1.0; ONEPLUS A5000 Build/OPM1.171019.011) MIOTWeex/2.0.2 (SmartHome;5.5.43;35D098176DB8665B0A7C711686A9539E;0.20.1;A;A7EDE321F22A8AC544FDAFAD13FC5DD8B6A53158;MI_APP_STORE;79QamcVRJwd7-sks) MIOTStore/20180406 (SmartHome;5.5.43;35D098176DB8665B0A7C711686A9539E;;A;A7EDE321F22A8AC544FDAFAD13FC5DD8B6A53158;MI_APP_STORE;79QamcVRJwd7-sks) APP/xiaomi.smarthome APPV/62916");
        heads.put("Host", "account.xiaomi.com");
        heads.put("Cookie", Cookie);
        heads.put("Connection", "Keep-Alive");
        heads.put("Accept-Encoding", "gzip");
        Map<String,String> responseMap = Utils.getXiomi(url,heads);

        JSONObject extensionpragma = JSONObject.parseObject(responseMap.get("extension-pragma"));
        String nonce = extensionpragma.getString("nonce");
        String ssecurity = extensionpragma.getString("ssecurity");

        byte[] s = encodeSHA1(("nonce="+nonce+"&"+ssecurity).getBytes());
        String _userIdNeedEncrypt = "true";
        String clientSign = Base64.encodeBase64String(s);
        String asdf = "&_userIdNeedEncrypt="+_userIdNeedEncrypt+"&clientSign="+URLEncoder.encode(clientSign);

        JSONObject jo = JSONObject.parseObject(responseMap.get("body").replaceAll("&&&START&&&", ""));
        String location = jo.getString("location");

        heads.put("Host", host);
        System.out.println(host+"---"+location+asdf);
        String bbb = Utils.get(location+asdf,heads);
        System.out.println("======222===="+bbb+"aaaaaa");
    }

    public static void aipIoComServerLogin() throws Exception {
        JSONObject jo = JSONObject.parseObject(Utils.retDatas.get("login").replaceAll("&&&START&&&", ""));
        JSONObject extensionpragma = JSONObject.parseObject(Utils.retDatas.get("extension-pragma"));

        String nonce = extensionpragma.getString("nonce");
        ssecurity = extensionpragma.getString("ssecurity");

        byte[] s = encodeSHA1(("nonce="+nonce+"&"+ssecurity).getBytes());
        String _userIdNeedEncrypt = "true";
        String clientSign = Base64.encodeBase64String(s);
        String asdf = "&_userIdNeedEncrypt="+_userIdNeedEncrypt+"&clientSign="+URLEncoder.encode(clientSign);

        String location = jo.getString("location");
        Map<String,String> heads = new HashMap<String,String>();
        heads = new HashMap<String,String>();

        heads.put("Content-Type", "application/x-www-form-urlencoded");
        heads.put("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 8.1.0; ONEPLUS A5000 Build/OPM1.171019.011) MIOTWeex/2.0.2 (SmartHome;5.5.43;35D098176DB8665B0A7C711686A9539E;0.20.1;A;A7EDE321F22A8AC544FDAFAD13FC5DD8B6A53158;MI_APP_STORE;79QamcVRJwd7-sks) MIOTStore/20180406 (SmartHome;5.5.43;35D098176DB8665B0A7C711686A9539E;;A;A7EDE321F22A8AC544FDAFAD13FC5DD8B6A53158;MI_APP_STORE;79QamcVRJwd7-sks) APP/xiaomi.smarthome APPV/62916");
        heads.put("Host", "sts.api.io.mi.com");
        heads.put("Connection", "Keep-Alive");
        heads.put("Accept-Encoding", "gzip");
        heads.put("Cookie", Cookie);
        Utils.get(location+asdf,heads);

        String yetAnotherServiceToken = " yetAnotherServiceToken="+Utils.cookies.get("serviceToken")+";";
        String serviceToken = " serviceToken="+Utils.cookies.get("serviceToken")+";";
        String userId = " userId="+Utils.cookies.get("userId")+";";
        Cookie = "";
        Cookie += userId;
        Cookie += yetAnotherServiceToken;
        Cookie += serviceToken;
        Cookie += " countryCode=CN; locale=zh_CN; timezone_id=Asia/Shanghai; timezone=GMT%2B08%3A00; is_daylight=0; dst_offset=0; channel=MI_APP_STORE";


    }

    public static String apiServer(String utlTmp,String info,String ssecurity,String cookie) throws Exception {

        ///////////////////
        long oauth_timestamp = System.currentTimeMillis();
        String _nonce = b(oauth_timestamp + 20000);
//        System.out.println(_nonce);
//        _nonce = "1mOvPOW4hvQBjd9g";
        String miyao = ssecurity;
        byte[] ddd = d(a(Base64.decodeBase64(miyao.getBytes()),Base64.decodeBase64(_nonce.getBytes())));

        String key = Base64.encodeBase64String(ddd);

        String data2 = utlTmp+"&"+key+"&"+_nonce+"&data="+info;

        String signature = b(data2,key);
        ////////////////
        String url = "https://api.io.mi.com/app"+utlTmp;
        HashMap<String, String> data = new HashMap<String,String>();
        data.put("_nonce", _nonce);
        data.put("signature", signature);
        data.put("data", info);


        Map<String, String> heads = new HashMap<String,String>();
        heads.put("Content-Type", "application/x-www-form-urlencoded");
        heads.put("Content-Length", data.toString().length()-2+"");
        heads.put("Host", "api.io.mi.com");
        heads.put("Connection", "Keep-Alive");
        heads.put("Accept-Encoding", "gzip");
        heads.put("X-XIAOMI-PROTOCAL-FLAG-CLI", "PROTOCAL-HTTP2");
        heads.put("Cookie", cookie);

        String ret = Utils.post(url, heads, data);
        return ret;
    }


    //控制开关
    public static String kongzhi(JSONObject sceneList,String index,String kg,String ssecurity,String cookie) throws Exception {
        JSONObject jsonInfo = sceneList.getJSONObject("result").getJSONObject(index);
        jsonInfo.getJSONObject("setting").put("enable", kg);

        String utlTmp = "/scene/editv2";
        String info = jsonInfo.toJSONString();
        apiServer(utlTmp,info,ssecurity,cookie);

        info = "{\"us_id\":\""+jsonInfo.getString("us_id")+"\",\"type\":1,\"status\":0,\"st_id\":15}";
        utlTmp = "/scene/setuserscene";
        return apiServer(utlTmp,info,ssecurity,cookie);
    }

    public static String shoudong(JSONObject sceneList,String index,String kg,String ssecurity,String cookie) throws Exception {
        JSONObject jsonInfo = sceneList.getJSONObject("result").getJSONObject(Integer.parseInt(index)+"");
        String us_id = jsonInfo.getString("us_id");

        String utlTmp = "/scene/start";
        String info = "{\"key\":\"click\",\"us_id\":\""+us_id+"\"}";
        return apiServer(utlTmp,info,ssecurity,cookie);
    }

    public static void main(String[] args) throws Exception {
        //登录
        login();
        aipIoComServerLogin();

        //获取数据
        String utlTmp = "/scene/list";
        String info = " {\"st_id\":15}";
        JSONObject sceneList = JSONObject.parseObject(apiServer(utlTmp,info,ssecurity,Cookie));

        JSONObject jsonInfo = sceneList.getJSONObject("result");

        for(Map.Entry<String, Object> entry : jsonInfo.entrySet()) {
            String key = entry.getKey();
            Map<String, Object> en = (Map<String, Object>) entry.getValue();

            System.out.println(key+"===="+en.get("name"));
        }

        //19台灯
        String taideng = "19";//台灯
        kongzhi(sceneList,taideng,"0",ssecurity,Cookie);

    }
    //HmacSHA256 key是base64 所以里面进行反转吗
    private static String b(String arg4, String arg5) throws Exception {
        String v0 = "";
        Mac v1 = Mac.getInstance("HmacSHA256");
        v1.init(new SecretKeySpec(Base64.decodeBase64(arg5.getBytes("UTF-8")), "HmacSHA256"));
        arg4 = Base64.encodeBase64String(v1.doFinal(arg4.getBytes("UTF-8")));
        return arg4;
    }
}


//Cookie += " passToken="+passToken+";";
//Cookie += userId;
//loginServer("https://account.xiaomi.com/pass/serviceLogin?_json=true&sid=passportapi","account.xiaomi.com");Thread.sleep(1500);
//loginServer("https://account.xiaomi.com/pass/serviceLogin?_json=true&sid=miotstore","shopapi.io.mi.com");Thread.sleep(1500);
//loginServer("https://account.xiaomi.com/pass/serviceLogin?_json=true&sid=xiaomihome","home.mi.com");Thread.sleep(1500);
//loginServer("https://account.xiaomi.com/pass/serviceLogin?_json=true&sid=ypsupport2","ypsupport2.kefu.mi.com");Thread.sleep(1500);
//loginServer("https://account.xiaomi.com/pass/serviceLogin?_json=true&sid=tsm-auth","tsmapi.pay.xiaomi.com");Thread.sleep(1500);
//loginServer("https://account.xiaomi.com/pass/serviceLogin?_json=true&sid=i.ai.mi.com","i.ai.mi.com");Thread.sleep(1500);
//loginServer("https://account.xiaomi.com/pass/serviceLogin?_json=true&sid=xiaoqiang","api.miwifi.com");Thread.sleep(1500);
//loginServer("https://account.xiaomi.com/pass/serviceLogin?_json=true&sid=mi_eshopm_go","m.mi.com");Thread.sleep(1500);
